package com.heking.qlyopensdkapp.ui;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


import com.heking.qlyopensdkapp.SharedPreferencesUtils;
import com.heking.qlyopensdkapp.R;
import com.heking.zplayer.qlyopen.Callback;
import com.heking.zplayer.qlyopen.IQlyPlayer;
import com.heking.zplayer.qlyopen.OnTalkListener;
import com.heking.zplayer.qlyopen.PlayError;
import com.heking.zplayer.qlyopen.PlayListener;
import com.heking.zplayer.qlyopen.QLYApi;
import com.heking.zplayer.qlyopen.QlyAccount;
import com.heking.zplayer.qlyopen.QlyPlayer;
import com.heking.zplayer.qlyopen.QlyToken;
import com.heking.zplayer.qlyopen.QlyTokenParams;
import com.heking.zplayer.qlyopen.ZQlyOpenSdk;

import java.io.File;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

/**
 * @Author: zhoug
 * @Date: 2024-11-05
 * @Description:
 */
public class QlyPlayActivity1 extends AppCompatActivity {
    private static final String TAG = ">>>QlyPlayActivity";
    private String mFirmId;
    private String mFirmName;
    private String mDeviceId="xxxxS_d4430e203f3e";
    protected String cacheImage;
    private Bitmap mWatermarkBitmap;//水印
    private QlyPlayer mPlayer;
    private boolean retry = true;
    private boolean btnPlayStatus = false;//播放按钮的状态
    private TextView mTopView;
    private FrameLayout mContainerPlayer;
    private ImageView mIvPlace;
    private ImageView mIvWatermark;
    private ProgressBar mProgressBar;
    private ImageView mBtnPlay;
    private TextView mTvError;
    private RelativeLayout mContainerVideo;
    private ImageView mIvTalk;
    private TextView mTvTalk;
    private LinearLayout mBtnTalking;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        beforeLayout(savedInstanceState);
        setContentView(getLayoutResID());
        findViews();
        addListener();
        initView();
        onCreateEnd(savedInstanceState);

    }

    /**
     * 设置布局文件之前执行
     *
     * @param savedInstanceState
     */
    public void beforeLayout(@Nullable Bundle savedInstanceState) {
        Intent intentExtras = getIntent();
       
    }

    /**
     * 布局文件id
     *
     * @return
     */
    public int getLayoutResID() {
        return R.layout.ativity_qly_play1;
    }

    /**
     * view初始化
     */
    public void findViews() {


        mTopView = findViewById(R.id.topView);
        mContainerPlayer = findViewById(R.id.containerPlayer);
        mIvPlace = findViewById(R.id.iv_place);
        mIvWatermark = findViewById(R.id.iv_watermark);
        mProgressBar = findViewById(R.id.progressBar);
        mBtnPlay = findViewById(R.id.btn_play);
        mTvError = findViewById(R.id.tv_error);
        mContainerVideo = findViewById(R.id.container_video);
        mIvTalk = findViewById(R.id.iv_talk);
        mTvTalk = findViewById(R.id.tv_talk);
        mBtnTalking = findViewById(R.id.btn_talking);
    }

    /**
     * 添加监听
     */
    public void addListener() {
        mContainerPlayer.setOnClickListener(v -> {
            if (mBtnPlay.getVisibility() == View.VISIBLE) {
                mBtnPlay.setVisibility(View.GONE);
            } else {
                mBtnPlay.setVisibility(View.VISIBLE);
            }
        });
    }

    public void initView() {

    }

    /**
     * onCreate 方法最后调用
     *
     * @param savedInstanceState
     */
    public void onCreateEnd(@Nullable Bundle savedInstanceState) {
        
        setTalkViewStatus(false);
        mPlayer = new QlyPlayer(this);
        mPlayer.setPlayViewGroup(mContainerPlayer);
        mPlayer.setMute(false);
        mPlayer.setPlayUrl(mDeviceId);
        mPlayer.setAutoGetAbility(false);
        mPlayer.setPlayListener(new PlayListener() {
            @Override
            public void onPlayStatusChange(int state) {
                switch (state) {
                    case IQlyPlayer.STATE_IDLE:
                        cancelPlayLoading();
                        setPlayButtonStatus(false);
                        showWatermark(false);
                        Log.d(TAG, "onPlayStatusChange:IDLE");
                        break;
                    case IQlyPlayer.STATE_START:
                        showPlayLoading();
                        setPlayButtonStatus(true);
                        hideError();
                        Log.d(TAG, "onPlayStatusChange:开始播放");
                        break;
                    case IQlyPlayer.STATE_PREPARED:
                        Log.d(TAG, "onPlayStatusChange:资源准备好了");
                        break;
                    case IQlyPlayer.STATE_PLAYING:
                        hideError();
                        cancelPlayLoading();
                        setPlayButtonStatus(true);
                        setPlaceImage(false);
                        if (mBtnPlay != null) {
                            mBtnPlay.postDelayed(() -> {
                                mBtnPlay.setVisibility(View.GONE);
                            }, 2000);
                        }
                        Log.d(TAG, "onPlayStatusChange:正在播放");
                        break;
                    case IQlyPlayer.STATE_PAUSE:
                        cancelPlayLoading();
                        setPlayButtonStatus(false);
                        Log.d(TAG, "onPlayStatusChange:暂停播放");
                        break;
                    case IQlyPlayer.STATE_ENDED:
                        cancelPlayLoading();
                        setPlayButtonStatus(false);
                        Log.d(TAG, "onPlayStatusChange:播放完成了");
                        break;

                }
            }

            @Override
            public void onPlayError(int code, String error) {
                Log.e(TAG, "onPlayError:code="+code+",error="+error);
                if (retry && code == PlayError.TOKEN_EXPIRE) {
                    Log.e(TAG, "token 过期 重新获取");
                    retry = false;
                    getOpenPlatformToken(new Callback<QlyToken>() {
                        @Override
                        public void onSuccess(QlyToken qlyToken) {
                            hideError();
                            mPlayer.startPlay();
                        }

                        @Override
                        public void onError(String error) {
                            showError(error);
                            cancelPlayLoading();
                            setPlayButtonStatus(false);
                        }
                    });
                } else {
                    cancelPlayLoading();
                    showError(error);
                    setPlayButtonStatus(false);
                }
            }
        });

        mPlayer.setOnTalkListener(new OnTalkListener() {
            @Override
            public void onTalkCallback(int status, String error) {
                toast(error);
            }
        });

        mBtnPlay.setOnClickListener(v -> {
            if (mPlayer != null) {
                if (btnPlayStatus) {
                    setPlayButtonStatus(false);
                    mPlayer.stopPlay();
                } else {
                    hideError();
                    setPlayButtonStatus(true);
                    mPlayer.startPlay();
                }
            }

        });

        mBtnTalking.setOnClickListener(v -> {
            if (!mPlayer.isPlaying()) {
                toast("视频没有播放");
                return;
            }
            if (mPlayer.isTalking()) {
                setTalkViewStatus(false);
                mPlayer.stopVoiceTalk();
            } else {
                setTalkViewStatus(true);
                mPlayer.startVoiceTalk();
            }
        });
        setPlaceImage(true);
        getOpenPlatformToken(null);
    }

    /**
     * 设置对讲状态
     *
     * @param talking
     */
    private void setTalkViewStatus(boolean talking) {
        if (talking) {
            mIvTalk.setImageResource(R.drawable.icon_video_video_talking);
            mIvTalk.setImageTintList(null);
            mTvTalk.setText("正在对讲");
        } else {
            mIvTalk.setImageResource(R.drawable.icon_video_video_talk);
            mIvTalk.setImageTintList(ColorStateList.valueOf(ContextCompat.getColor(getActivity(), R.color.textColor)));
            mTvTalk.setText("开启对讲");
        }
    }

    /**
     * 获取token
     *
     * @param callback
     */
    private void getOpenPlatformToken(Callback<QlyToken> callback) {
        QlyToken qlyToken = SharedPreferencesUtils.getMonitorToken(mDeviceId);
        if (qlyToken != null && !qlyToken.isExpired()) {
            ZQlyOpenSdk.setOpenPlatformToken(qlyToken.getToken());
            if (callback != null) {
                callback.onSuccess(qlyToken);
            }
            return;
        }
        Log.d(TAG, "获取token");
        QlyTokenParams params = new QlyTokenParams();
        params.setAppId(QlyAccount.appId);
        params.setSecret(QlyAccount.secret);
        params.setOperatorType(ZQlyOpenSdk.TOKEN_OPERATOR_TYPE_CUSTOM);
        params.setTargetType(ZQlyOpenSdk.TARGET_TYPE_DEVICE);
        params.setTarget(mDeviceId);
        params.setAction(ZQlyOpenSdk.ACTION_WRITE);

        QLYApi.getOpenPlatformToken(params, new Callback<QlyToken>() {
            @Override
            public void onSuccess(QlyToken qlyToken) {
                Log.d(TAG, "获取设备token成功:");
                SharedPreferencesUtils.setMonitorToken(mDeviceId, qlyToken);
                ZQlyOpenSdk.setOpenPlatformToken(qlyToken.getToken());
                if (callback != null) {
                    callback.onSuccess(qlyToken);
                }
            }

            @Override
            public void onError(String error) {
                Log.e(TAG, "获取设备token失败:" + error);
                if (callback != null) {
                    callback.onError(error);
                } else {
                    showError(error);
                }
            }
        });
    }


    /**
     * 显示错误信息
     *
     * @param error
     */
    protected void showError(String error) {
        if (mTvError == null) {
            return;
        }
        if (error == null) {
            mTvError.setText("");
            mTvError.setVisibility(View.GONE);
        } else {
            mTvError.setText(error);
            mTvError.setVisibility(View.VISIBLE);
        }
    }

    protected void hideError() {
        if (mTvError != null) {
            mTvError.setText("");
            mTvError.setVisibility(View.GONE);
        }
    }

    /**
     * 改变播放按钮状态
     *
     * @param btnPlayStatus 是否在播放
     */
    protected void setPlayButtonStatus(boolean btnPlayStatus) {
        if (mBtnPlay == null) return;
        if (btnPlayStatus) {
            mBtnPlay.setImageResource(R.drawable.icon_monitor_stop);
        } else {
            mBtnPlay.setImageResource(R.drawable.icon_monitor_play);
        }
        this.btnPlayStatus = btnPlayStatus;
    }


    /**
     * 显示视频加载框
     */
    protected void showPlayLoading() {
        if (mProgressBar != null) {
            mProgressBar.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏视频加载框
     */
    protected void cancelPlayLoading() {
        if (mProgressBar != null) {
            mProgressBar.setVisibility(View.GONE);
        }
    }

    /**
     * 设置占位图
     *
     * @param visibility
     */
    protected void setPlaceImage(boolean visibility) {
       /* try {
            if (visibility && mIvPlace != null) {
                mIvPlace.setVisibility(View.VISIBLE);
                //占位图为空时使用企业图片
                String imageUrl = null;
                if (StringUtils.isNullOrEmpty(imageUrl)) {
                    FirmInfo en_firmInfo = LoginUserLiveData.getFirmInfo();
                    if (en_firmInfo != null) {
                        imageUrl = en_firmInfo.getFirmImage();
                    }
                }
                if (imageUrl != null && !"".equals(imageUrl)) {
//                    ZImageLoader.load(getActivity(), mIvPlace, ComFileUtils.getRealUrl(imageUrl), R.drawable.monitor_image_default, R.drawable.monitor_image_default, null);
                    MyImageLoader.with(getActivity())
                            .load(imageUrl)
                            .placeholder(R.drawable.monitor_image_default)
                            .error(R.drawable.monitor_image_default)
                            .into(mIvPlace);
                } else {
                    //没有占位图
                    if (imageExists(cacheImage)) {
                        //加载缓存的截屏图片
//                        ZImageLoader.load(getActivity(), mIvPlace, cacheImage);
                        MyImageLoader.with(getActivity())
                                .placeholder(R.drawable.monitor_image_default)
                                .error(R.drawable.monitor_image_default)
                                .load(cacheImage)
                                .into(mIvPlace);
                    } else {
                        //加载默认图片
//                        ZImageLoader.load(getActivity(), mIvPlace, R.drawable.monitor_image_default);
                        MyImageLoader.with(getActivity())
                                .load(R.drawable.monitor_image_default)
                                .into(mIvPlace);
                    }
                }
            } else if (mIvPlace != null) {
                mIvPlace.setVisibility(View.GONE);
            }
        } catch (Exception e) {
        }
        if (visibility) {
            showWatermark(false);
        } else {
            showWatermark(true);
        }*/
    }

    protected boolean imageExists(String path) {
        if (path != null) {
            File file = new File(path);
            if (file.exists() && file.length() > 0) {
                return true;
            }
        }
        return false;
    }


    /**
     * 显示/隐藏视频水印
     *
     * @param show
     */
    protected void showWatermark(boolean show) {
       /* if (mIvWatermark == null) {
            return;
        }
        if (show) {
            if (mWatermarkBitmap == null) {
                mWatermarkBitmap = WatermarkUtils.createWatermarkBitmap();
            }
            if (mWatermarkBitmap != null) {
                mIvWatermark.setImageBitmap(mWatermarkBitmap);
                setWatermarkVisibility(true);
            } else {
                setWatermarkVisibility(false);
            }
        } else {
            setWatermarkVisibility(false);
        }*/
    }

    /**
     * 设置水印的显示状态
     *
     * @param show
     */
    private void setWatermarkVisibility(boolean show) {
        if (mIvWatermark != null) {
            mIvWatermark.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayer != null) {
            mPlayer.release();
        }

    }

    //#######################################
    protected void toast(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    protected void logAndToastE(String tag, String msg){
        Log.e(tag, msg);
        toast(msg);
    }

    protected void logAndToastD(String tag, String msg){
        Log.d(tag, msg);
        toast(msg);
    }
    
    protected AppCompatActivity getActivity(){
        return this;
    }
}
